/**
 * 搜索条件
 * @param value 输入框的值
 * @param record 操作的行数据
 * @param getRef  获取参照数据
 * @param refDataSource 参照数据源
 */
import { Component } from "react";
import { Row, Col, FormControl, Button, Collapse } from 'tinper-bee';
import "./index.less";
import Icon from 'bee-icon';
import 'bee-icon/build/Icon.css';
import GirdRefer from './Grid/index.jsx'
import ReferSingleSelect from './ReferSingleSelect/index.jsx'
import TreeRef from './TreeRef/index.jsx'
import RangePicker from '../RangePicker/index.jsx'

import { vendorsSetStorage, vendorsGetStorage, vendorsDanger, vendorsFmtDate, vendorsGetUrlParam } from 'utils/config.js';

class SearchPanel extends Component {
    constructor(props) {
        super(props)
        this.state = {
            open: true,
            values: this.setInitValues(),
            items: props.items
        }
        this.search = {
            getSearchValue: this.getSearchValue,
            setSearchItemDisabled: this.setSearchItemDisabled,
            emptySearchItemValue: this.emptySearchItemValue
        }
        //初始化缓存
        this.initCache()
    }

    getSearchValue = ({ refPk, requireKey }) => {
        let { dataSource } = this.props;
        let { items } = this.state;
        let cacheData = vendorsGetStorage(dataSource)
        if (cacheData[refPk] && cacheData[refPk]['selectedList'].length) {
            let selectRows = cacheData[refPk]['selectedList'];
            let selectKeyS = []
            selectRows.forEach((row) => {
                if (typeof (requireKey) !== 'string') {
                    if (row[requireKey[0]]) {
                        selectKeyS.push(row[requireKey[0]])
                    } else {
                        selectKeyS.push(row[requireKey[1]])
                    }
                } else {
                    selectKeyS.push(row[requireKey])
                }
            })
            return selectKeyS
        } else {
            return []
        }
    }
    emptySearchItemValue = (refPk, item) => {
        let { dataSource } = this.props,
            cacheData = vendorsGetStorage(dataSource),
            values = this.state.values;
        if (cacheData[refPk] && cacheData[refPk]['selectedList'].length) {
            for (let key in cacheData) {
                if (cacheData.hasOwnProperty(key) && cacheData[key] && key == refPk) {
                    cacheData[key]['refData'] = [];
                    cacheData[key]['selectedList'] = [];
                    cacheData[key]['refData'] = '';
                    cacheData[key]['reqData'] = '';
                }
            }

            values[refPk].value = ''
            this.setState({
                values
            }, () => {
                    vendorsSetStorage(dataSource, cacheData)
                    this.props.searchAfterEvent && this.props.searchAfterEvent(refPk)
            })
        } else {
            if (item && item.itemtype === "section-date") {
                values[refPk] = { startTime: '', endTime: '' }
                this.setState({
                    values
                })
            }
        }
    }
    handleEmptyItem = (item) => {
        this.emptySearchItemValue(item.refPk, item)
    }
    setSearchItemDisabled = (refPk, isDisabled) => {
        let { items } = this.state;
        items.map(item => {
            if (item.refPk == refPk) {
                item.disabled = isDisabled
            }
            return item
        })
        this.setState({
            items
        })
    }
    initCache = () => {
        let { dataSource } = this.props;
        let { items } = this.state;
        let cacheData = vendorsGetStorage(dataSource)
        if (!cacheData) {
            let initData = {}
            items.forEach((item, index) => {
                initData[item.refPk] = null
            })
            initData.values = null;
            vendorsSetStorage(dataSource, initData)
        } else {
            console.log(cacheData)
            for (let key in cacheData) {
                if (cacheData.hasOwnProperty(key) && cacheData[key]) {
                    cacheData[key]['refData'] = [];
                    cacheData[key]['selectedList'] = [];
                    cacheData[key]['refData'] = '';
                    cacheData[key]['reqData'] = '';
                }
            }
            vendorsSetStorage(dataSource, cacheData)
        }
    }
    showRefer = ({ item, index }) => {
        let { refType, isMultiSelectedEnabled } = item;
        if (refType === 'grid') {
            let reqData = item.reqRef.queryCondition && item.reqRef.queryCondition.call(this);
            if (isMultiSelectedEnabled) {
                this.GridRefer.showGrid({ item, index, reqData, dataSource: this.props.dataSource })
            } else {
                this.ReferSingleSelect.showGrid({ item, index, reqData, dataSource: this.props.dataSource })
            }
        } else if (refType === 'tree') {
            let reqData = item.reqRef.queryCondition && item.reqRef.queryCondition.call(this);
            this.TreeRef.showGrid({ item, index, reqData, dataSource: this.props.dataSource })
        }
    }

    changeShowSearch = () => {
        this.setState({
            open: !this.state.open
        })
    }
    setInitValues = () => {
        let values = {};
        this.props.items.forEach((item, index) => {
            if (item.itemtype === "section-date") {
                values[item.refPk] = { startTime: '', endTime: '' };
            } else {
                values[item.refPk] = { value: '', display: '' };
            }
        })
        return values
    }
    onTimeChange = (timeArr, item) => {
        let values = this.state.values;
        console.log(timeArr)
        let startTime = vendorsFmtDate(timeArr[0]);
        let endTime = vendorsFmtDate(timeArr[1]);
        values[item.refPk].startTime = startTime;
        values[item.refPk].endTime = endTime;
        this.setState({
            values
        }, () => {
        })
    };
    onInputChange = (e, item) => {
        let values = this.state.values;
        values[item.refPk].value = e.target.value;
        values[item.refPk].display = e.target.value;
        this.setState({
            values
        }, () => {
        })
    }
    upDataValues = (key, value) => {
        let values = this.state.values;
        values[key].value = value,
            console.log(values)
        this.setState({
            values
        }, () => {
            this.props.searchAfterEvent && this.props.searchAfterEvent(key)
        })
    }
    renderItemByItemType = ({ item, index }) => {
        let { itemtype, refPk, label, disabled = false } = item;
        let { values } = this.state;
        if (itemtype === 'refer') {
            return <div className='icon-po'>
                <FormControl
                    disabled={disabled}
                    placeholder={`请输入${label}`}
                    className='search-panel-item-input ref-input'
                    value={values[refPk].value}
                />

                <Icon
                    type="uf-navmenu"
                    className='search-panel-item-input-icon'
                    onClick={() => {
                        if (disabled) return;
                        this.showRefer.call(this, {
                            item, index
                        })
                    }}
                />
                {
                    values[item.refPk].value || values[item.refPk].startTime ?
                        <Icon className='item-empty-icon' type="uf-close-c-o" onClick={() => {
                            this.handleEmptyItem(item)
                        }} /> :
                        null
                }

            </div>
        } else if (itemtype === 'section-date') {
            return <div className='icon-po'>
                <RangePicker
                    disabled={disabled}
                    className='search-panel-item-input'
                    startTime={values[refPk].startTime}
                    endTime={values[refPk].endTime}
                    item={item}
                    onChange={this.onTimeChange}
                />
                {
                    values[item.refPk].value || values[item.refPk].startTime ?
                        <Icon className='item-empty-icon' type="uf-close-c-o" onClick={() => { this.handleEmptyItem(item) }} /> :
                        null
                }
            </div>
        } else if (itemtype === 'input') {
            return <div className='icon-po'>
                <FormControl
                    disabled={disabled}
                    value={values[refPk].value}
                    placeholder={`请输入${label}`}
                    showClose={true}
                    onChange={(e) => {
                        console.log(e)
                        this.onInputChange(e, item)
                    }}
                    className='search-panel-item-input'
                />
                {
                    values[item.refPk].value || values[item.refPk].startTime ?
                        <Icon className='item-empty-icon' type="uf-close-c-o" onClick={() => { this.handleEmptyItem(item) }} />
                        : null
                }
            </div>
        }
    }
    renderItem = ({ item, index }) => {
        let { name, col } = this.props,
            { items, values } = this.state,
            { required, label, itemtype } = item;
        return <Col md={col} xs={col} sm={col} key={index}>
            <div className="search-panel-item">
                <div className='search-panel-item-label'>
                    {required ? <span className='search-panel-item-required'>*</span> : null}
                    {label}
                </div>

                < div className='search-panel-item-inputBox'>
                    {this.renderItemByItemType({ item, index })}
                </div>

            </div>
        </Col >
    }
    getSearchData = () => {
        let { dataSource } = this.props;
        let { items } = this.state;
        let { values } = this.state;
        let cacheData = vendorsGetStorage(dataSource);
        let selectedS = {};
        let reStr = ["必输:"];

        items.forEach(item => {
            if (item.itemtype === 'refer') {

                let selected = []
                cacheData[item.refPk] && cacheData[item.refPk]['selectedList'] && cacheData[item.refPk]['selectedList'].length && cacheData[item.refPk]['selectedList'].forEach((citem) => {
                    let ses = citem[item.refPk] ? citem[item.refPk] : citem[item.refPk1];
                    selected.push(ses)
                })
                selectedS[item.refPk] = selected;
                item.required && !selected.length && (reStr.push(`${item.label}`))

            } else {
                if (item.itemtype === 'section-date') {
                    selectedS[item.refPk] = values[item.refPk]
                } else {
                    selectedS[item.refPk] = values[item.refPk].value
                }
            }
        })
        return { selectedS, reStr }
    }
    searchBtnClick = () => {
        let { selectedS, reStr } = this.getSearchData()
        console.log(reStr)
        if (reStr.length > 1) {
            vendorsDanger({
                'text': <div>
                    {
                        reStr.map((item, index) => {
                            if (index == 0) {
                                return (
                                    <div>{item}</div>
                                )
                            } else {
                                return (
                                    <div style={{ textIndent: "2em" }}>{item}</div>
                                )
                            }
                        })
                    }
                </div>
            })
            return;
        }
        this.props.searchBtnClick(selectedS)
    }
    emptyBtnClick = () => {
        this.setState({
            values: this.setInitValues()
        }, () => {
            this.initCache()
        })
    }
    render() {
        let { name, col } = this.props;
        let { items } = this.state;
        return (
            <div className='search-panel'>
                <Row>
                    <Col md={12} xs={12} sm={12}>
                        <div className='search-panel-name'>
                            {name}
                            <Button className='icon-open-btn' onClick={this.changeShowSearch}>
                                {this.state.open ? "展开" : "收起"}
                                <Icon type={this.state.open ? "uf-treearrow-down" : "uf-gridcaretarrowup"} />
                            </Button>
                        </div>
                    </Col>
                    {
                        this.state.open ? items.map((item, index) => {
                            return this.renderItem({ item, index })
                        }) : null
                    }
                    {this.state.open ? <Col md={col} xs={col} sm={col}>
                        <div className="search-panel-item-button">
                            <Button colors="primary" className='icon-search-btn' onClick={this.searchBtnClick}>
                                <Icon type="uf-search" />
                            </Button>
                            <Button className='icon-qingkong-btn' onClick={this.emptyBtnClick}>
                                <Icon type='uf-qingkong' />
                            </Button>
                        </div>
                    </Col> : null}
                </Row>

                <TreeRef ref={el => { this.TreeRef = el }} upDataValues={this.upDataValues} />
                <GirdRefer ref={el => { this.GridRefer = el }} upDataValues={this.upDataValues} />
                <ReferSingleSelect ref={el => { this.ReferSingleSelect = el }} upDataValues={this.upDataValues} />
            </div>
        )
    }
    componentWillUnmount() {

    }
}

function YGCCreateSearch  (searchTpl, events) {
    return <SearchPanel
        ref={child => this.searchC = child}
        {...searchTpl}
        {...events}
    />
}

export default YGCCreateSearch;